package com.blank.shop.security.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <br/>Date 2021/9/10
 * <br/>Time 1:15:38
 *
 * @author _blank
 */
@Slf4j
@Controller
public class ValidateCodeController {

    public static final String SESSION_CAPTCHA_KEY = "SESSION_CAPTCHA_KEY";

    @RequestMapping(path = {"/code/image"}, method = {RequestMethod.GET})
    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        final CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);

        // millis当做是否过期标识
        final String code = System.currentTimeMillis() + "::" + captcha.getCode();

        final ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
        servletWebRequest.setAttribute(SESSION_CAPTCHA_KEY, code, RequestAttributes.SCOPE_SESSION);

        response.setContentType(MediaType.IMAGE_PNG_VALUE);

        captcha.write(response.getOutputStream());
    }

    @RequestMapping(path = {"/code/sms"}, method = {RequestMethod.GET})
    public ResponseEntity<Object> createSmsCode(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
        final String code = RandomUtil.randomString(RandomUtil.BASE_NUMBER, 4);

        final ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
        servletWebRequest.setAttribute(SESSION_CAPTCHA_KEY, code, RequestAttributes.SCOPE_SESSION);

        final String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
        log.info("向手机号: {}发送短信验证码: {}", mobile, code);

        return ResponseEntity.ok("短信已发送，请注意查收！");
    }

}
